﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using System.Collections.Specialized;

namespace WebLearningFS
{
	public class WebQuest
	{
		private readonly string username;
		private readonly string password;
		private readonly int type;
		public List<ClassFile> ClassMaterials { get; set; }
		public List<SpaceFile> SpaceMaterials { get; set; }
		public Dictionary<string, string> FileLink { get; set; }
		private CookieAwareWebClient wc;

		private readonly string loginURL = "http://learn.tsinghua.edu.cn/MultiLanguage/lesson/teacher/loginteacher.jsp";
		private readonly string courseURL = "http://learn.tsinghua.edu.cn/MultiLanguage/lesson/student/download.jsp?course_id=90653";
		private readonly string spaceURL = "http://166.111.4.50/vspace/personal_space/person_info.jsp";
		private readonly string transURLa = "http://learn.tsinghua.edu.cn/vspace.jsp";
		private readonly string ticketURL = "http://zhjw.cic.tsinghua.edu.cn/j_acegi_login.do?url=/zhjw.do&ticket=";
		private readonly string uploadURL = "http://166.111.4.50/cgi-bin/upload.cgi";
		private readonly string stepA = "http://166.111.4.50/thns_move_2.jsp";
		private readonly string deleteURL = "http://166.111.4.50/vspace/personal_space/action/do_edit.jsp?action=delete";
		//private readonly string http://166.111.4.50/thns_move.jsp?usercookie={0}--";
		private string tmp_ = "";

		public void Login()
		{
			if (type == 1)
			{
				Console.WriteLine("Web Learning Class Materials Login Started.");

				string param = string.Format("userid={0}&userpass={1}&submit1=%B5%C7%C2%BC", username, password);
				wc.UploadString(loginURL, param);
				tmp_ = wc.DownloadString(courseURL);
				ParseHtml(tmp_);

				Console.WriteLine("Web Learning Class Materials Login Finished.");
				return;
			}
			if (type == 2)
			{
				Console.WriteLine("Virtual Space Login Started.");

				string param = string.Format("userid={0}&userpass={1}&submit1=%B5%C7%C2%BC", username, password);
				wc.UploadString(loginURL, param);

				wc.DownloadString(ticketURL);

				tmp_ = wc.DownloadString(transURLa);
				int start = tmp_.IndexOf("http");
				int end = tmp_.LastIndexOf('"');
				tmp_ = tmp_.Substring(start, end - start);
				wc.DownloadString(tmp_);

				tmp_ = wc.DownloadString(stepA);
				tmp_ = wc.DownloadString(spaceURL);
				ParseHtml(tmp_);
				Console.WriteLine("Virtual Space Login Finished.");
				return;
			}
		}

		public byte[] Download(string URL)
		{
			return wc.DownloadData(URL);
		}

		public void DeleteFile(string filename)
		{
			//Intended for virtual space
			string param = string.Format("pathRela=&thisPage=person_info.jsp%3Fpath%3D%26subdir%3D&checkbox1={0}", Uri.EscapeUriString(filename));
			//Console.WriteLine(tmp_);
			tmp_ = wc.UploadString(deleteURL, param);
			Console.WriteLine(tmp_);
			return;
		}

		public void UploadFile(byte[] buffer, string filename)
		{
			//System.IO.FileStream filestream = new System.IO.FileStream("D:\\upload.txt", System.IO.FileMode.Open);
			//byte[] buffer = new byte[filestream.Length];
			//filestream.Read(buffer, 0, buffer.Length);
			//filestream.Close();
			NameValueCollection nvc = new NameValueCollection();
			nvc.Add("path", "");
			nvc.Add("errorURL", "/uperror.jsp?error=");
			nvc.Add("returnURL", string.Format("/vspace/personal_space/action/do_upload.jsp?owner={0}", username));
			nvc.Add("newfilename", "");
			nvc.Add("v_remain", "104857588");
			wc.PostFile(buffer, filename, uploadURL, nvc);
		}

		//TEST USE
		public static void Write2File(string lines)
		{
			System.IO.StreamWriter file = new System.IO.StreamWriter("D:\\a.txt", false);
			file.WriteLine(lines);
			file.Close();
		}

		public static void Write2Bin(byte[] buffer)
		{
			System.IO.FileStream filestream = new System.IO.FileStream("D:\\down", System.IO.FileMode.OpenOrCreate);
			filestream.Write(buffer, 0, buffer.Length);
			filestream.Close();
		}

		private void ParseHtml(string html)
		{
			HtmlDocument doc = new HtmlDocument();
			doc.LoadHtml(html);
			if (type == 1)
			{
				HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//tr[@class]");
				var ret = new List<ClassFile>();
				if (links == null)
					return;
				foreach (var link in links)
				{
					HtmlNode meta = link.ChildNodes[3];
					HtmlNode head = link.ChildNodes[5];
					//HtmlNode size = link.ChildNodes[9];
					HtmlNode date = link.ChildNodes[11];

					ClassFile cf = new ClassFile();
					MatchCollection mc = Regex.Matches(meta.InnerText, @"getfilelink=([\w\W]+?)_\d+(\.\w+?)&");
					if (mc.Count == 1)
					{
						cf.Meta = mc[0].Groups[1].Captures[0].Value + mc[0].Groups[2].Captures[0].Value;
					}
					cf.Head = head.InnerText.Trim();
					//cf.Size = size.InnerText.Trim();
					cf.Date = date.InnerText.Trim();
					cf.Link = @"http://learn.tsinghua.edu.cn/" + link.ChildNodes[5].Descendants("a").First().Attributes["href"].Value;
					cf.Size = wc.GetFileSize(cf.Link).ToString();
					ret.Add(cf);
					FileLink[cf.Meta] = cf.Link;
				}
				ClassMaterials = ret;
				return;
			}
			if (type == 2)
			{
				HtmlNodeCollection links = doc.DocumentNode.SelectNodes("//a[@href != \"./help/index.htm\" and @target]");
				var ret = new List<SpaceFile>();
				if (links == null)
					return;
				foreach (var link in links)
				{
					SpaceFile sf = new SpaceFile();
					sf.Link = @"http://166.111.4.50" + link.Attributes[0].Value;
					sf.Head = link.InnerText;
					sf.Size = wc.GetFileSize(sf.Link).ToString();
					ret.Add(sf);
					FileLink[sf.Head] = sf.Link;
				}
				SpaceMaterials = ret;
				return;
			}

		}

		private void InitWc()
		{
			wc = new CookieAwareWebClient();
			if (type == 1) wc.Encoding = Encoding.UTF8;
			wc.Proxy = null;
			wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
			wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)";
		}

		public WebQuest(string username, string password, int type)
		{
			this.username = username;
			this.password = password;
			this.type = type;
			this.FileLink = new Dictionary<string, string>();
			InitWc();
		}

		public static void Main()
		{
		}
	}

	public class ClassFile
	{
		public string Meta { get; set; }
		public string Link { get; set; }
		public string Head { get; set; }
		public string Size { get; set; }
		public string Date { get; set; }
	}
	public class SpaceFile
	{
		public string Link { get; set; }
		public string Size { get; set; }
		public string Head { get; set; }
		public string Date { get; set; }
	}
}
